#include "Tank.h"
#include "Application.h"
#include <Math.h>
#include <algorithm>

void cat::Tank::think()
{
	float tvx = cosf(_input.angle) * _input.velocity * 5;
	float tvy = sinf(_input.angle) * _input.velocity * 5;

	_vx += (tvx - _vx) * 0.1f;
	_vy += (tvy - _vy) * 0.1f;

	_x += _vx;
	_y += _vy;

	_x = std::max(10.f, _x);
	_x = std::min(790.f, _x);

	_y = std::max(10.f, _y);
	_y = std::min(790.f, _y);

	_cannonY -= (_cannonY - _cannonTargetY) * 0.2;

	_visual.gunLeft.setOrigin(-7.f + _cannonY, 12.f);
	_visual.gunRight.setOrigin(-7.f + _cannonY, -8.f);

	if(_burstFrameTimer >=0)
	{
		if(_burstFrameTimer == 10)
		{
			FireLeft();
			FireRight();
			_cannonY = 10;
		}

		if(_burstFrameTimer == 5)
		{
			FireLeft();
			FireRight();
			_cannonY = 10;
		}

		if(_burstFrameTimer == 0)
		{
			FireLeft();
			FireRight();
			_cannonY = 10;
		}

		_burstFrameTimer--;
	}
}

void cat::Tank::draw()
{
	sf::RenderWindow& window = cat::Application::current().getWindow();

	_visual.turret.setPosition(_x, _y);
	window.draw(_visual.turret);

	_visual.gunLeft.setPosition(_x, _y);
	_visual.gunLeft.setRotation(_turretDirection * 180.f / 3.1415f);
	window.draw(_visual.gunLeft);

	_visual.gunRight.setPosition(_x, _y);
	_visual.gunRight.setRotation(_turretDirection * 180.f / 3.1415f);
	window.draw(_visual.gunRight);
}

void cat::Tank::setVelocity(float velocity)
{
	_input.velocity = velocity;
}

void cat::Tank::move(float angle, float velocity)
{
	_input.angle = angle;
	_input.velocity = velocity;
}

void cat::Tank::turretTarget(float x, float y)
{
	_turretDirection = atan2f(y - _y, x - _x);
}

void cat::Tank::FireLeft()
{
	cat::Application::current().getBulletFactory().create(
		_x + 11.f * cosf(_turretDirection) + 10.f * sinf(_turretDirection), 
		_y - 10.f * cosf(_turretDirection) + 11.f * sinf(_turretDirection),
		_turretDirection);
}

void cat::Tank::FireRight()
{
	cat::Application::current().getBulletFactory().create(
		_x + 11.f * cosf(_turretDirection) - 10.f * sinf(_turretDirection), 
		_y + 10.f * cosf(_turretDirection) + 11.f * sinf(_turretDirection), 
		_turretDirection);
}

void cat::Tank::fire()
{
	_burstFrameTimer = 15;
}


cat::Tank::Tank()
{
	_visual.turret.setRadius(10.f);
	_visual.turret.setOrigin(10.f, 10.f);
	_visual.turret.setFillColor(sf::Color(255u,255u,255u,30u));
	_visual.turret.setOutlineColor(sf::Color::Red);
	_visual.turret.setOutlineThickness(1.f);

	_visual.gunLeft.setSize(sf::Vector2f(10.f, 5.f));
	_visual.gunLeft.setFillColor(sf::Color::Red);
	_visual.gunLeft.setOutlineColor(sf::Color(0,0,0,100u));
	_visual.gunLeft.setOutlineThickness(1.f);

	_visual.gunRight.setSize(sf::Vector2f(10.f, 5.f));
	_visual.gunRight.setFillColor(sf::Color::Red);
	_visual.gunRight.setOutlineColor(sf::Color(0,0,0,100u));
	_visual.gunRight.setOutlineThickness(1.f);

	_x=10.f;
	_y=10.f;
	_vx = 0.f;
	_vy = 0.f;

	_input.angle = 0.f;
	_input.velocity = 0.f;

	_cannonTargetY = 0.f;
	_cannonY = 0.f;
}


cat::Tank::~Tank(void)
{
}
